package com.haier.npt.security.api;


import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.haier.npt.common.JsonResult;
import com.haier.npt.exception.BizBaseException;
import com.haier.npt.security.domain.SysApp;
import com.haier.npt.security.i18n.SecurityExceptionCode;
import com.haier.npt.security.resource.SysAppResource;
import com.haier.npt.security.service.SysAppService;

@RestController
@RequestMapping("/apps")
public class SysAppController implements SysAppResource {

    @Autowired
    private SysAppService sysAppService;

    /**
     * 添加一个app
     *
     * @param sysApp
     * @return
     */
    @Override
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public JsonResult<SysApp> addApp(@RequestBody @Valid SysApp sysApp) {
        return JsonResult.success(this.sysAppService.addApp(sysApp));
    }

    /**
     * 更新一个app
     *
     * @param sysApp
     * @return
     */
    @Override
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public JsonResult<Boolean> updateApp(@RequestBody @Valid SysApp sysApp) {
        return JsonResult.success(this.sysAppService.updateApp(sysApp));
    }

    /**
     * 查询数据库中的app
     */
    @Override
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public JsonResult<List<SysApp>> listApps() {
        return JsonResult.success(sysAppService.listApp());
    }

    /**
     * 验证appkey的有效性
     *
     * @param sysApp
     * @return
     */
    @Override
    @RequestMapping(value = "/validate", method = RequestMethod.POST)
    public JsonResult<SysApp> valiteAppKey(@RequestBody SysApp sysApp) {
        // 任何一个项为空， 则返回false
        if (sysApp == null || sysApp.getApp_key() == null || sysApp.getApp_secret() == null) {
            throw new BizBaseException(SecurityExceptionCode.ILLEGAL_ARGUMENT);
        }
        SysApp dbsysApp = sysAppService.valiteAppKey(sysApp.getApp_key(), sysApp.getApp_secret());
        return JsonResult.success(dbsysApp);
    }
}
